"""Main entry point for Skype Shell.

Copyright Ian Blumel, 2009.
All Rights Reserved.
"""

try:
    import psyco
    psyco.profile()
except ImportError:
    pass # Ok, we tried.

import sys
import Skype4Py

from libskysh.cmd import cmd_t, cmderr_t


RECIEVED = intern("RECIEVED")
SENT = intern("SENT")
SENDING = intern("SENDING")
RECIEVED = intern("RECEIVED")
READ = intern("READ")


class _logger_t(object):
    def __init__(self):
        self.lvl = 0
    def __call__(self, lvl, fmt, args=()):
        print lvl, self.lvl
        if lvl <= self.lvl:
            sys.stdout.write(fmt % args)
LOG = _logger_t()


    

class load_cmd_t(cmd_t):
    _USAGE = """load [plugin]
Will load a specific plugin from a directory. The plugin will be
automatically scanned and intergrated.
"""

    def __init__(self, *args, **kws):
        cmd_t.__init__(self, *args, **kws)
        self.name = "load"
        self.type = SENDING
        self._is_help = False
        self._file = None

    def _parse(self, argv):
        # Low budget for now, no need to do any silly parsing.
        try:
            arg = argv[1]
        except IndexError:
            raise cmderr_t(
                ("error: load requires one argument, "
                 "type load -h for more details")
                )
        if arg in ["--help", "-h"]:
            self._is_help = True
        else:
            self._file = arg

    def execute(self, argv):
        self._parse(argv)
        if self._is_help:
            self.stdout.write(self._USAGE)
        else:
            raise NotImplementError


class skshl_t(object):
    def __init__(self):
        self.skype = Skype4Py.Skype()
        print self.skype
        self.skype.OnMessageStatus = self.on_msg_stat

        # Install the built-in commands.
        self.cmds = [google_cmd_t()]
        self._chk_cmds()

    def _chk_cmds(self):
        # Check that the properties are defined.
        for cmd in self.cmds:
            if not hasattr(cmd, "name"):
                print >>sys.stderr, "%s is missing name attribute" % (`cmd`)
            elif not hasattr(cmd, "type"):
                print >>sys.stderr, "%s is missing type attribute" % (`cmd`)

    def attach(self):
        self.skype.Attach()

    def on_msg_stat(self, msg, stat):
        argv = cmd_parser(msg.Body)
        for cmd in self.cmds:
            if cmd.type == stat and cmd.match(argv[0]):
                cmd.wire_cmd(msg, stat)
                try:
                    cmd.execute(argv)
                except cmd_err_t, e:
                    self.error("error: " + str(e))

